package BehavioralPattern.Iterator;

/**
 * @Classname : ConcreteIterator
 * @Description : 具体迭代器
 * @Author : chentianyu
 * @Date 2023/3/5 15:13
 */


public class ConcreteIterator implements Iterator {
    private int cursor = 0;

    private Aggregate aggregate;

    public ConcreteIterator(Aggregate aggregate) {
        this.aggregate = aggregate;
    }

    @Override
    public Object next() {
        Object object = null;
        if (cursor < aggregate.getList().size()) {
            object = aggregate.getList().get(cursor++);
        }
        return object;
    }

    @Override
    public boolean hasNext() {
        return cursor < aggregate.getList().size();  // 注意最后一个元素也认为有后继元素
    }

    @Override
    public boolean remove() {
        if (aggregate.getList().isEmpty()) return false;
        aggregate.getList().remove(cursor);
        return true;
    }
}
